"use client";

import dataProviderSimpleRest from "@refinedev/simple-rest";
import axios from "axios";
import Cookies from "js-cookie";

const API_URL = "/api";

// 创建 Axios 实例，添加认证头
const axiosInstance = axios.create({
  baseURL: '',
});

// 添加请求拦截器，自动添加认证头
axiosInstance.interceptors.request.use((config) => {
  const authToken = Cookies.get("auth");
  if (authToken) {
    config.headers.Authorization = `Bearer ${authToken}`;
  }
  return config;
});

const localProvider = dataProviderSimpleRest(API_URL, axiosInstance);

const resource = {
    ...localProvider,
}
const parseResponse = (response: Promise<any>) => {
    return new Promise((resolve, reject) => {
        response.then((res) => {
            resolve(res.data);
        }).catch((err) => {
            reject(err);
        });
    });
};

resource.getOne = (args: any) => {
    const res = localProvider.getOne(args);
    return parseResponse(res) as any;
}

export const dataProvider = resource;
